//
//  RecordChangeViewController.m
//  BDD_TWO
//
//  Created by XTW on 2023/6/9.
//

#import "RecordChangeViewController.h"
#import "SeeAudio.h"
#import "AVPlayerManager.h"
#import "CustomLineView.h"
#import "UIView_extension.h"
#import "FileManager.h"
#import "FMAudioPlayer.h"
#import "RecordChangeCollectionViewCell.h"
#import "LocalRecordModel.h"

@interface RecordChangeViewController ()<FMAudioPlayerDelegate, UIScrollViewDelegate, UIGestureRecognizerDelegate> {
    CGFloat duration;
    CGFloat currentTime;
    BOOL isDragging;
    NSArray *dataArr;
    NSInteger selectRow;
}
@property (weak, nonatomic) IBOutlet UIImageView *bg;
@property (weak, nonatomic) IBOutlet UIScrollView *waveScrollView;
@property (weak, nonatomic) IBOutlet UIScrollView *scrollView;
@property (weak, nonatomic) IBOutlet UIButton *actionBtn;
@property (weak, nonatomic) IBOutlet UILabel *timeLabel;
@property (weak, nonatomic) IBOutlet UICollectionView *collectionView;
@property (nonatomic, strong) CustomLineView *line;
@property (nonatomic, strong) FMAudioPlayer *player;

@end

@implementation RecordChangeViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"变声";
    [self addBackBtn];
    [((UIButton *)[self addRigthBtn:@"完成"]) addTarget:self action:@selector(donePress) forControlEvents:UIControlEventTouchUpInside];
    [self initView];

    if (self.model.needSaveUrl) {
        [self seeAudio:self.model.needSaveUrl];
    } else {
        [self seeAudio:[NSURL fileURLWithPath:[[FileManager sharedManager] getLocalFilePath:self.model.fileName]]];
    }
    // Do any additional setup after loading the view from its nib.
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [self.player stop];
}

- (void)donePress {
    [self loadingHUDAlert:@"正在处理"];
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.01 * NSEC_PER_SEC)), dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        NSString *recordName = dateTurnTimeNameStr([NSDate date]);
        NSString *outPath = [AVPlayerManager getTmpRecordName:[NSString stringWithFormat:@"%@.wav", recordName]];
        [self.player save:outPath type:self->selectRow complete:^(BOOL success) {
            dispatch_async(dispatch_get_main_queue(), ^{
                [self hideHudAlert];
                if (self.ReloadHandle) {
                    self.ReloadHandle([NSURL fileURLWithPath:outPath], self.title);
                }
                [self goBackAction];
            });
        }];
    });
}

- (IBAction)actionPress {
    self.actionBtn.selected = !self.actionBtn.selected;
    if (!self.actionBtn.selected) {
        [self.player pause];
    } else {
        self.player.type = selectRow;
        [self.player startWithStyle];
    }
}

- (IBAction)resetPress {
    [self.player pause];
    selectRow = 0;
    [self.collectionView reloadData];
}

- (void)seeAudio:(NSURL *)url {
    dispatch_async(dispatch_get_main_queue(), ^{
        [self.waveScrollView.subviews makeObjectsPerformSelector:@selector(removeFromSuperview)];
    });
    self.player = [[FMAudioPlayer alloc] initWithPath:[url.absoluteString stringByReplacingOccurrencesOfString:@"file://" withString:@""]];
    self.player.delegate = self;
    [self.player play_ready];
    
    AVURLAsset  *asset = [[AVURLAsset alloc] initWithURL:url options:nil];
    self->duration = CMTimeGetSeconds(asset.duration);
    __weak __typeof(self) weakSelf = self;
    [SeeAudio renderPNGAudioPictogramLogForAsset:asset done:^(UIImage *spectrumImage,UIImage *scaleImage,NSInteger imageWidth) {
        dispatch_async(dispatch_get_main_queue(), ^{
            [self hideHudAlert];
            [weakSelf.waveScrollView setContentSize:CGSizeMake(imageWidth, 0)];
            UIImageView *imgv = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, imageWidth, 280)];
            imgv.image = spectrumImage;
            [weakSelf.waveScrollView addSubview:imgv];
            UIImageView *scaleImgv = [[UIImageView alloc] initWithFrame:CGRectMake(0, 280, imageWidth, 30)];
            scaleImgv.image = scaleImage;
            [weakSelf.waveScrollView addSubview:scaleImgv];
            
        });
    }];
}

- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView {
    isDragging = YES;
    [self.player pause];
    self.actionBtn.selected = NO;
}

- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate {
    isDragging = NO;
    int totalMs = [self.player get_total_seconds];
    [self.player set_current_pos:(int)totalMs*(currentTime/duration)];
}

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
    int totalMs = [self.player get_total_seconds];
    [self.player set_current_pos:(int)totalMs*(currentTime/duration)];
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    if (self.waveScrollView == scrollView) {
        currentTime = (scrollView.contentOffset.x/(scrollView.contentSize.width-SCREEN_WIDTH_DEVICE))*duration;
        if (currentTime > duration) {
            currentTime = duration;
        } else if (currentTime <= 0) {
            currentTime = 0;
        }
        int currentMin  = (int)currentTime / 60;
        int currentSecond  = (int)currentTime % 60;
        int millisecond = (currentTime - currentSecond)*100 - currentMin*60*100;
        NSString *currentTime1 = [NSString stringWithFormat:@"%.2d:%.2d.%02d",currentMin,currentSecond, millisecond];
        self.timeLabel.text = currentTime1;
    }
}

#pragma mark ---FMAudioPlayerDelegate---
- (void)timeRunScale:(CGFloat)scale {
    currentTime = duration*scale;
    int allMin  = (int)currentTime / 60;
    int allSecond  = (int)currentTime % 60;
    int allMillisecond  = (currentTime - allSecond)*100;
    NSString *aullTime = [NSString stringWithFormat:@"%.2d:%.2d.%02d",allMin,allSecond, allMillisecond];
    self.timeLabel.text = aullTime;
    
    CGFloat pointX = (self.waveScrollView.contentSize.width-SCREEN_WIDTH_DEVICE)*scale;
    if (pointX < self.waveScrollView.contentOffset.x) {
        pointX = self.waveScrollView.contentOffset.x;
    }
    [UIView animateWithDuration:0.1 animations:^{
        [self.waveScrollView setContentOffset:CGPointMake(pointX, 0) animated:NO];
    }];
}

- (void)trackPlayDidEnd {
    self.actionBtn.selected = NO;
    [self.waveScrollView setContentOffset:CGPointMake(0, 0) animated:YES];
}

#pragma mark UICollectionView

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return dataArr.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    static NSString * CellIdentifier = @"RecordChangeCell";
    RecordChangeCollectionViewCell * cell = [collectionView dequeueReusableCellWithReuseIdentifier:CellIdentifier forIndexPath:indexPath];
    [cell showContent:indexPath.row selectRow:selectRow name:[dataArr objectAtIndex:indexPath.row]];
    return cell;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    selectRow = indexPath.row;
    [self.collectionView reloadData];
}

- (void)initView {
    [self.bg setFrame:CGRectMake(0, IS_iPhoneX_Top + NavBarHeight + 280, SCREEN_WIDTH_DEVICE, SCREEN_HEIGHT_DEVICE - (IS_iPhoneX_Top + NavBarHeight + 280))];
    [self.scrollView setFrame:CGRectMake(0, IS_iPhoneX_Top + NavBarHeight + 310, SCREEN_WIDTH_DEVICE, SCREEN_HEIGHT_DEVICE - IS_iPhoneX_Bottom - IS_iPhoneX_Top - NavBarHeight - 310)];
    [self.scrollView setContentSize:CGSizeMake(0, 300)];
    [self.waveScrollView setFrame:CGRectMake(0, IS_iPhoneX_Top + NavBarHeight, SCREEN_WIDTH_DEVICE, 310)];
    [self.view addSubview:self.line];
    dataArr = [NSArray arrayWithObjects:@"原声", @"萝莉", @"惊悚", @"大叔", @"搞笑", @"空旷", @"机器人", @"合唱", nil];
    selectRow = 0;
    [self configCollectionView];
    [self.collectionView reloadData];
}

- (void)configCollectionView {
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
    layout.itemSize = CGSizeMake(54, 54);
    layout.scrollDirection = UICollectionViewScrollDirectionVertical;
    layout.sectionInset = UIEdgeInsetsMake(0, 30, 0, 30);
    layout.minimumInteritemSpacing = 30;
    layout.minimumLineSpacing = 20;
    self.collectionView.collectionViewLayout = layout;
    self.collectionView.backgroundColor = [UIColor clearColor];
    [self.collectionView registerClass:[RecordChangeCollectionViewCell class] forCellWithReuseIdentifier:@"RecordChangeCell"];
}

- (CustomLineView *)line {
    if (!_line) {
        _line = [[CustomLineView alloc] initCustomView:CGRectMake((SCREEN_WIDTH_DEVICE-3)/2.0, IS_iPhoneX_Top + NavBarHeight, 3, 280)];
    }
    return _line;
}

@end
